package com.example.charpter06;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class DatabaseActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_database;
    private String mdatabaseName;
    private String desc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database);
        tv_database = findViewById(R.id.tv_database);
        findViewById(R.id.btn_database_create).setOnClickListener(this);
        findViewById(R.id.btn_database_delete).setOnClickListener(this);
        mdatabaseName = getFilesDir() +"/test.db";
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_database_create:
                //创建数据库。数据库如果存在就打开他，不存在就创建它
               SQLiteDatabase db =  openOrCreateDatabase(mdatabaseName, Context.MODE_PRIVATE,null);
               String desc =String.format("数据库%s创建%s",db.getPath(),(db!=null)?"成功":"失败");
               tv_database.setText(desc);
                break;
            case R.id.btn_database_delete:
                //删除数据库
                boolean result = deleteDatabase(mdatabaseName);
                desc = String.format("数据库%s删除%s",mdatabaseName,result?"成功":"失败");
                tv_database.setText(desc);
                break;
        }
    }
}